using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace RedBlueBalls
{
    /// <summary>
    /// A class to load the red blue ball records from a CSV file
    /// </summary>
    public class RecordLoader
    {
        /// <summary>
        /// Load records from file
        /// </summary>
        /// <param name="filename"></param>
        public static RedBlueBallRecord[] LoadFromFile(string filename)
        {
            int line = 0;
            int record = 0;
            List<RedBlueBallRecord> records = new List<RedBlueBallRecord>();
            using (StreamReader reader = File.OpenText(filename))
            {
                string str = "";
                while ((str = reader.ReadLine()) != null)
                {
                    line++;
                    try
                    {
                        RedBlueBallRecord redBlueBall = new RedBlueBallRecord(str);
                        records.Add(redBlueBall);
                        record++;
                    }
                    catch (Exception e)
                    {
                        Tracer.AppendMessage("Exception occurs when reading the data " + e.ToString());
                    }
                }
            }

            Tracer.AppendMessage(String.Format("Read {0} lines, {1} records", line, record));
            Tracer.ShowMessage();

            return records.ToArray();
        }
    }
}
